<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2024/3/19
 * Time: 16:22
 */

namespace app\zyhsmarketing\lib;

use app\zyhsapi\model\ZyhsUser;
use app\zyhsapi\model\ZyhsUserAccount;
use app\zyhsapi\model\ZyhsUserAccountRecord;
use app\zyhsapi\model\ZyhsUserPush;
use GuzzleHttp\Exception\GuzzleException;
use think\Controller;
use think\Log;
use XznsTools\curl\Curl;

class RyMArk extends Controller
{

    protected $key = [
        'ios' => [
            'key' => '0e39c2473f704f41a6b248946d6552be',
            'secret' => '840AC0ACB4310CD12648AC385BA9FC99'
        ],
        'android' => [
            'key' => '935997d88cf90250d19f39aa23a9ab0d',
            'secret' => '49C516D402F8B2787B43EBB318F60FF7'
        ]
    ];

    protected $url = 'https://log.trackingio.com';

    /**
     * @url http://newdoc.trackingio.com/Rest%E4%BB%98%E8%B4%B9%E6%8A%A5%E9%80%81%E8%AF%B4%E6%98%8E%E6%96%87%E6%A1%A3.html  热云充值打点
     * @param $tradeType [自定义] alipay(支付宝)  unionpay(银联) weixinpay(微信) yeepay(易宝支付) applepay(苹果支付)
     * @param $orderId
     * @return void
     * @throws GuzzleException
     */
    public function recharge($tradeType, $orderId)
    {
        try
        {
            $netInfo = $this->getNetInfo();
            $ordersInfo = (new ZyhsUserAccountRecord())->where('order_id', $orderId)->find();
            if ($ordersInfo)
            {
                $pushInfo = (new ZyhsUserPush())->getUserRegid((int)$ordersInfo['uid']);
                if (!$pushInfo)
                {
                    return;
                }
                $phoneType = in_array($pushInfo['push_type'], [2, 3, 4, 5], true) ? 'android' : 'ios';
                if ($phoneType === 'ios')
                {
                    if (!empty($pushInfo['only_code']))
                    {
                        $deviceid = $onlyCode = $pushInfo['only_code'];
                    } else
                    {
                        $onlyCode = '00000000-0000-0000-0000-000000000000';
                        $deviceid = isset($pushInfo['idfv']) ? 'IFV_' . $pushInfo['idfv'] : '00000000-0000-0000-0000-000000000000';
                    }
                    $ryDeviceId = (new ZyhsUser())->getInfoById($ordersInfo['uid'], ['id', 'regid']);
                    if ($ryDeviceId)
                    {
                        $deviceid = $ryDeviceId['regid'];
                    }
                } else
                {
                    if (!empty($pushInfo['only_code']))
                    {
                        $deviceid = $onlyCode = $pushInfo['only_code'];
                    } else
                    {
                        return;
                    }
                }
                $userInfo = (new ZyhsUser())->getInfoById($ordersInfo['uid']);
                $goodsInfo = (new ZyhsUserAccount())->coinGoods($phoneType === 'ios', $userInfo);
                $context = [
                    '_deviceid' => $deviceid,
                    '_transactionid' => $orderId,
                    '_paymenttype' => $tradeType,
                    '_currencytype' => 'CNY',
                    '_currencyamount' => $ordersInfo['total_amount'],
                    '_ip' => $netInfo['ip'],
                    '_ipv6' => $netInfo['ipv6'],
                    '_tz' => '+8',
                    '_ryos' => $phoneType,
                    '_model' => $pushInfo['model'],
                    '_pkgname' => 'com.zhunle.rtc',
                    'param1' => $goodsInfo[$ordersInfo['gid']]['coin_num']
//                '_ryosversion' => '',
//                '_app_version' => '',
//                '_lib_version' => '',
//                '_timestamp' => '',
//                'param4' => '',
                ];
                if ($phoneType === 'ios')
                {
                    $context['_idfa'] = $onlyCode;
                } else
                {
//                    $context['_imei'] = $onlyCode;
//                    $context['_androidid'] = $onlyCode;
                    $context['_oaid'] = $onlyCode;
//                    $context['_mac'] = $netInfo['mac'];
                }
                $res = Curl::request($this->url . '/receive/tkio/payment', [
                    'appid' => $this->key[$phoneType]['key'],
                    'who' => $ordersInfo['uid'],
                    'context' => $context
                ], 'post', ['Content-Type' => 'application/json'], 'json');
                Log::write('热云充值打点记录:' . $tradeType . '-' . $orderId . '-' . json_encode($res, JSON_UNESCAPED_UNICODE), 'log', true);
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()热云充值打点异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
    }

    /**
     * 获取请求来源网络信息
     * @return string[]
     */
    protected function getNetInfo()
    {
        $data = [
            'ip' => '',
            'ipv6' => '',
            'mac' => ''
        ];
        // 获取 IP 地址
        $data['ip'] = $_SERVER['REMOTE_ADDR'] ?? '';
        // 获取 MAC 地址（可能不总是可用，具体取决于客户端和网络环境）
        $data['mac'] = $_SERVER['HTTP_CLIENT_MAC'] ?? '';
        // 处理 IPv6 地址（如果存在）
        if (strpos($data['ip'], ':') !== false)
        {
            $data['ipv6'] = explode(':', $data['ip'])[0];
        }
        return $data;
    }
}
